// pages/user/user.js
var http = require('../../utils/rquest.js')
Page({
  /**
   * 页面的初始数据
   */
  data: {
    num:1,
    active: 0,
    storeName:'',
    tempFilePaths: [],
    list: [],
    dwclist: [],
    dshlist: [],
    ywclist: [],
    orderid: '',
    index: 0,
    currentobj: {
      0: 1,
      1: 1,
      2: 1
    },
    dwctotal: 0,
    dshtotal: 0,
    ywctotal: 0
  },

  //登陆按钮
  loginbtn() {
    wx.reLaunch({
      url: '../login/login',
    })
  },

  //退出登录
  outlogin(){
    wx.removeStorage({
      key: 'userMsg'
    })
  },

  //获取图片
  getImg() {
    var hant = this;
    let imgs = []
    wx.chooseImage({
      count: 4,
      sizeType: ['original', 'compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        imgs = res.tempFilePaths
        if (hant.data.tempFilePaths.length == 0) {
          hant.setData({
            tempFilePaths: imgs
          })
        } else {
          hant.setData({
            tempFilePaths: hant.data.tempFilePaths.concat(imgs)
          })
        }
      }
    })
  },
  //删除图片
  deleimg(e) {
    let imgs = this.data.tempFilePaths
    imgs.splice(e.currentTarget.dataset.index, 1)
    this.setData({
      tempFilePaths: imgs
    })
    this.onLoad()
  },
  //tab切换事件
  onChange(event) {
    this.setData({
      active: event.detail.index
    })
    wx.showToast({
      title: `切换到标签 ${event.detail.name}`,
      icon: 'none',
      dialog: false
    });
    this.getAll()
  },

  //获取数据列表
  getAll(options) {
    let status = "daiwancheng"
    switch (this.data.active) {
      case 0:
        status = "daiwancheng"
        break
      case 1:
        status = "daishenhe"
        break
      case 2:
        status = "yiwancheng"
        break
    }
    http.orderGetAll({
        orderStatus: status,
        creatorId: wx.getStorageSync('userMsg').id,
        current: this.data.currentobj[this.data.active]
      })
      .then(res => {
        let arr = res.data.msg.list;
        let taskType = '';
        let imgs = [];
        let status = '';
        let orderSta = '';
        let dwTotal = Math.ceil(res.data.msg.total / res.data.msg.pageSize)
        let msTotal = Math.ceil(res.data.msg.total / res.data.msg.pageSize)
        let ywTotal = Math.ceil(res.data.msg.total / res.data.msg.pageSize)
        if (res.data.status == 'fail') {
          wx.showToast({
            title: res.data.msg,
          })
        }

        //处理数据中的值
        if (arr instanceof Array) {
          for (var i = 0; i < arr.length; i++) {
            switch (arr[i].task.taskType) {
              case "task_type_1":
                taskType = "普通任务"
                break
              case "task_type_2":
                taskType = "中级任务"
                break
              case "task_type_3":
                taskType = "高级任务"
                break
            }
            switch (arr[i].orderSta) {
              case "daiwancheng":
                status = "待完成"
                break;
              case 'daishenhe':
                orderSta = '待审核'
                break;
              case 'yiwancheng':
                orderSta = '已完成'
                break;
              case "weitongguo":
                status = "未通过"
                break
            }
            arr[i].orderSta = orderSta
            arr[i].task.taskType = taskType
            imgs = arr[i].task.fileUids.split(',')
            imgs.pop()
            imgs.shift()
            arr[i].task.fileUids = imgs
            arr[i].orderStatus = status
          }
        }
        this.setData({
          list: arr
        })

        // 不同内容不同total
        if (this.data.active == 0) {
          this.setData({
            dwctotal: dwTotal
          })
          if (this.data.currentobj[0] == 1) {
            //如果是当前页我就给你赋值
            this.setData({
              dwclist: arr
            })
          } else {
            if (options == "缓存") {
              this.setData({
                dwclist: this.data.dwclist
              })
            } else {
              //如果不是当前页我就给你拼接新数据
              this.setData({
                dwclist: this.data.dwclist.concat(arr)
              })
            }
          }
        } else if (this.data.active == 1) {
          this.setData({
            dshtotal: msTotal
          })
          if (this.data.currentobj[1] == 1) {
            //如果是当前页我就给你赋值
            this.setData({
              dshlist: arr
            })
          } else {
            //如果是提交或者删除就还让等于缓存的数据
            if (options == "缓存") {
              this.setData({
                dshlist: this.data.dshlist
              })
            } else {
              //如果不是当前页我就给你拼接新数据
              this.setData({
                dshlist: this.data.dshlist.concat(arr)
              })
            }

          }
        } else if (this.data.active == 2) {
          this.setData({
            ywctotal: ywTotal
          })
          if (this.data.currentobj[2] == 1) {
            //如果是当前页我就给你赋值
            this.setData({
              ywclist: arr
            })
          } else {
            if (options == "缓存") {
              this.setData({
                ywclist: this.data.ywclist
              })
            } else {
              //如果不是当前页我就给你拼接新数据
              this.setData({
                ywclist: this.data.ywclist.concat(arr)
              })
            }

          }
        }
      })
  },
  //上一页
  prevent() {
    let keys = "currentobj." + this.data.active
    this.setData({
      [keys]: 1
    })
    this.getAll()
  },
  //下一页
  next() {
    let dwccurrent = this.data.currentobj[0]
    let dsgcurrent = this.data.currentobj[1]
    let ywccurrent = this.data.currentobj[2]
    let keyone = 'currentobj.0'
    let keytow = 'currentobj.1'
    let three = 'currentobj.2'
    if (this.data.active === 0 && dwccurrent !== this.data.dwctotal) {
      dwccurrent++
      this.setData({
        [keyone]: dwccurrent
      })
      this.getAll()
    }

    if (this.data.active === 1 && dsgcurrent !== this.data.dshtotal) {
      dsgcurrent++
      this.setData({
        [keytow]: dsgcurrent
      })
      this.getAll()
    }

    if (this.data.active === 1 && ywccurrent !== this.data.ywctotal + 1) {
      ywccurrent++
      this.setData({
        [keythree]: ywccurrent
      })
      this.getAll()
    }
  },
  //预览图片
  previewImg(e) {
    let arr = e.currentTarget.dataset.imglist.map(function(item) {
      return 'https://app.yueluo.club/file/5gmaiq/' + item
    })
    wx.previewImage({
      current: e.currentTarget.dataset.flag, // 当前显示图片的http链接
      urls: arr // 需要预览的图片http链接列表
    })
  },

  //打开dialog
  commit(row) {
    this.setData({
      dialog: true,
      orderid: row.currentTarget.dataset.orderid
    });
  },
  onClose() {
    this.setData({
      dialog: false
    });
  },
  //复制链接按钮
  copyText: function(e) {
    wx.setClipboardData({
      data: e.currentTarget.dataset.text,
      success: function(res) {
        wx.getClipboardData({
          success: function(res) {
            wx.showToast({
              title: '复制成功'
            })
          }
        })
      }
    })
  },

  //上传完成凭证确定按钮
  updateBtn() {
    if (this.data.tempFilePaths.length < 1) {
      wx.showToast({
        title: '请选择一张图片',
      })
      return
    }
    let thant = this
    http.orderSubmit({
        orderId: this.data.orderid,
        creatorId: wx.getStorageSync('userMsg').id
      })
      .then(res => {
        this.formdata(res.data.attId)
      })
  },

  //图片上传
  formdata(attid) {
    let tant = this;
    let i = this.data.index
    let leng = this.data.tempFilePaths.length - 1;
    wx.uploadFile({
      url: "https://app.yueluo.club/5gmaiquan/order/submitOrderFile",
      filePath: this.data.tempFilePaths[i], //chooseImage上传的图片
      name: 'file', //需要传给后台的图片字段名称
      formData: {
        orderId: this.data.orderid,
        creatorId: wx.getStorageSync('userMsg').id,
        attId: attid
      }, //需要传给后台的其他表单数据
      header: {
        "Content-Type": "multipart/form-data", //form-data格式
        'Accept': 'application/json',
      },
      success(res) {
        let arr = JSON.parse(res.data)
        if (arr.msg == 0) {
          if (i == leng) {
            //上传完成
            tant.setData({
              index: 1
            })
            wx.showToast({
              title: '成功',
            })
            wx.reLaunch({
              url: './user',
            })
           
            //调用删除缓存函数
            tant.deletedata("提交")
          } else {
            i++
            tant.setData({
              index: i
            })
            tant.formdata(attid)
          }
        } else {
          wx.showToast({
            title: '失败',
          })
        }
      },
      fail: function(res) {
        wx.showToast({
          title: res.errMsg,
        })
      }
    })
  },

  //删除缓存中数据
  deletedata(val) {
    let contrast = ""
    let arr = this.data.dwclist;
    if (val === "提交") {
      contrast = this.data.orderid
    } else {
      contrast = val
    }
    for (var i = 0; i < arr.length; i++) {
      if (arr[i].id === contrast) {
        arr.splice(i, 1)
      }
    }
    this.setData({
      dwclist: arr
    })
    this.setData({
      dialog: false,
    })
    this.getAll("缓存")
  },

  //取消任务
  delete(row) {
    http.orderRemove({
        taskId: row.currentTarget.dataset.orderid,
        creatorId: wx.getStorageSync('userMsg').id
      })
      .then(res => {
        if (res.data.status == 'success') {
          wx.showToast({
            title: res.data.msg,
          })
          this.deletedata(row.currentTarget.dataset.orderid)
        } else {
          wx.showToast({
            title: '取消失败',
          })
        }
      })
      .catch(err => {
        wx.showToast({
          title: err,
        })
      })
  },


  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    // 判断导航长度做传参使用
    let role = wx.getStorageSync('userMsg').roleList
    if (role === "role_admin" || role === "role_superAdmin") {
      this.setData({
        num: 4
      })
    } else {
      this.setData({
        num: 1
      })
    }



    if (wx.getStorageSync('userMsg').name){
      this.setData({
        storeName: wx.getStorageSync('userMsg').name
      })
    }else{
      this.setData({
        storeName:""
      })
    }
    let keys = "currentobj." + this.data.active
    this.setData({
      [keys]: 1
    })
    this.getAll()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {
  },

  //监听tabbar点击
  onTabItemTap(item) {
    if (getCurrentPages().length != 0) {
      //刷新当前页面的数据
      getCurrentPages()[getCurrentPages().length - 1].onLoad()
    }
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})